<?php

/**
 * HTML5端 用户中心API文件
 * User: poptser
 * Email:poptser@foxmail.com
 * Date: 2016/8/13
 * Time: 10:25
 */
namespace SDXApi\Controller;

use Think\Controller;
use Think\Log;
class HduserController extends Controller {
	
	/*
	 * hd用户微信登录回调
	 */
	public function login_callback() {
		if (! IS_POST) {
			returnApiError ( 'error request' );
		}
		$wx_user_info = I ( 'post.wx_user_info' );
		$userinfo = json_decode ( base64_decode($wx_user_info) ,true);
		
		$res = $this->init_user($userinfo);
		
		if($res){
			returnApiSuccess($res);
		}else{
			returnApiError('登录失败');
		}
	}
	
	/**
	 * ios手机登录
	 */
	public function user_login_4IP() {
		$phone = I("post.phone");
		$smscode = I("post.smscode");
		$has_weixin = I('has_weixin');
		if( !empty($phone) && !empty($smscode) ) {
			$ver_code = S($phone."_code");

            if($smscode != 698888 || $phone != '15220002185'){
                if($smscode!=$ver_code){
                    returnApiError('验证码不正确');
                }
            }

			$users = M("users")->field("password,paypwd",true)->where(array("mobile_phone"=>$phone))->find();

			if($users){
				$Return_data = $users;
				$wechat_user = M("wechat_user")->field("openid,nickname,headimgurl")->where(array("ect_uid"=>$users['user_id']))->find();
				if($wechat_user){
					$Return_data['nickname']= $wechat_user['nickname'];
					$Return_data['headimgurl']= $wechat_user['headimgurl'];
					$Return_data['openid']= $wechat_user['openid'];
				}else{
					$Return_data['nickname']= "";
					$Return_data['headimgurl']= "";
					$Return_data['openid']= "";
				}
				$Return_data['uid']= $users['user_id'];
				$Return_data['point']= $users['user_money'];
				$Return_data['phone']= $users['mobile_phone'];
	
				D("Users")->update_user_info($users['user_id']); //更新用户登录信息
	
				returnApiSuccess($Return_data,"登录成功");
			}else{
				if($has_weixin){
					$res = array();
					$res['is_regrist'] = 0;
					returnApiError("获取用户信息失败",$res);
				}else{
					//新用户--自动注册账号
					$username = 'wx_' . gmtime().mt_rand(1, 99);
					$password = 'shidexian';
					$other = array('phone'=>$phone);
					$re = D('Users')->register($username,$password,$username."@shidexian.com",$other);
					if($re){
						$userinfo = M('Users')->field("password,paypwd",true)->where(array('user_id'=>$re))->find();
						$userinfo['nickname']= $userinfo['user_name'];
						$userinfo['headimgurl']= "";
						$userinfo['openid']= "";
						$userinfo['uid']= $users['user_id'];
						$userinfo['point']= $users['user_money'];
						$userinfo['phone']= $users['mobile_phone'];
					}
					return $userinfo;//返回用户UID 和用户微信相关信息
				}
			}
		}else {
			returnApiError("请输入手机号与验证码");
		}
	}
	
	/**
	 *发送验证码
	 */
	public function get_verification_code(){
		$user_phone = I("post.phone");
		if($user_phone){
			$ver_code = getSmsCode();
			$send_result = A("Smsapi")->send_message_api("ver_code",$user_phone,'ios用户登录',0,0,$ver_code,0);
			if($send_result){
				S($user_phone."_code",$ver_code,600);    //验证码保持600秒
				returnApiSuccess(null,'发送验证码成功');
			}else{
				returnApiError('发送验证码失败');
			}
		}else{
			returnApiError("请输入正确的手机号");
		}
	}
	
	/**
	 * 初始化用户
	 */
	public function init_user($userinfo) {
		if(empty($userinfo ['unionid'])){
			returnApiError('获取微信用户信息失败，请重试');
		}
		$data = M ( 'wechat_user' )->where ( array (
				'unionid' => $userinfo ['unionid'] 
		) )->find (); // 判断用户是否在微信用户表
		if (! $data) {
			// 新用户--自动注册账号
			$username = 'wx_' . time () . mt_rand ( 1, 99 );
			$password = 'shidexian';
			
			$re = D ( 'Users' )->register ( $username, $password, $username . "@shidexian.com", null );
			if ($re) {
				// 获取用户信息
				if ($userinfo) {
					$userinfo ['ect_uid'] = $re;
					M ( 'wechat_user' )->add ( $userinfo ); // 将数据写入微信用户表
				}
				$userinfo ['uid'] = $re;
				return $userinfo; // 返回用户UID 和用户微信相关信息
			} else {
				returnApiError('登录失败，请重新登录');
			}
		} else {
			if ($userinfo) {
				// 不更新openid，只有公众号网页授权才更新
				$openid = $userinfo ['openid'];
				unset ( $userinfo ['openid'] );
				M ( 'wechat_user' )->where ( 'ect_uid=' . $data ['ect_uid'] )->save ( $userinfo ); // 更新微信用户表中
			}
			// 老用户，返回账号信息
			$userinfo ['uid'] = $data ['ect_uid'];
			$openid = M ( 'wechat_user' )->where ( array (
					'unionid' => $userinfo ['unionid'] 
			) )->getField ( 'openid' );
			$userinfo ['openid'] = $openid;
			return $userinfo; // 返回用户UID 和用户微信相关信息
		}
	}
	
	public function test(){
		$string = '{"openid":"ofFj0v_kLmVz-PcLGzqvqFQ7eH3k","nickname":"我不是陈小亮","sex":1,"language":"zh_CN","city":"Huizhou","province":"Guangdong","country":"CN","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/JrrHoiaSrNp40icicltD1ChBn0F8RkP0I7S8uiabKicAjBIsibJyQIMCkZXkW4GibX0icGDZbIFukZ2ibpVsia8Oia8iaTMWDaJWffbrcHFic\/0","privilege":[],"unionid":"o3kA9v7bTkjfJxGxMMalZJ7YgRsE"}';
		$userinfo = json_decode($string,true);
		$res = $this->init_user($userinfo);
		dump($res);
		
	}
	
	public function write_log($message,$filename){
		$log = new Log();
		$destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';
		
		$log->write($message,'DEBUG','',$destination);
	}
}